package com.zyz.friend.service.userquestion.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.zyz.api.RemoteJudgeService;
import com.zyz.api.model.UserExeResult;
import com.zyz.api.model.dto.JudgeSubmitDTO;
import com.zyz.api.model.vo.UserQuestionResultVO;
import com.zyz.common.core.constants.Constants;
import com.zyz.common.core.enums.ProgramType;
import com.zyz.common.core.enums.QuestionResType;
import com.zyz.common.core.enums.ResultCodeEnum;
import com.zyz.common.core.model.Result;
import com.zyz.common.core.utils.ThreadLocalUtil;
import com.zyz.common.security.exception.ServiceException;
import com.zyz.friend.elasticsearch.QuestionRepository;
import com.zyz.friend.mapper.question.QuestionMapper;
import com.zyz.friend.mapper.usersubmit.UserSubmitMapper;
import com.zyz.friend.model.question.Question;
import com.zyz.friend.model.question.es.QuestionES;
import com.zyz.friend.model.userquestion.QuestionCase;
import com.zyz.friend.model.userquestion.dto.UserSubmitDTO;
import com.zyz.friend.model.usersubmit.UserSubmit;
import com.zyz.friend.rabbitmq.JudgeProducer;
import com.zyz.friend.service.userquestion.IUserQuestionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Slf4j
@Service
public class UserQuestionServiceImpl implements IUserQuestionService {

    @Autowired
    private QuestionRepository questionRepository;

    @Autowired
    private QuestionMapper questionMapper;

    @Autowired
    private RemoteJudgeService remoteJudgeService;

    @Autowired
    private JudgeProducer judgeProducer;

    @Autowired
    private UserSubmitMapper userSubmitMapper;

    @Override
    public Result<UserQuestionResultVO> submit(UserSubmitDTO userSubmitDTO) {
        // 先判断语言类型
        if (ProgramType.JAVA.getCode().equals(userSubmitDTO.getProgramType())) {
            // 按照java逻辑处理
            JudgeSubmitDTO judgeSubmitDTO = assembleJudgeSubmitDTO(userSubmitDTO);
            // 调用openfeign
            return remoteJudgeService.doJudgeJavaCode(judgeSubmitDTO);
        }
        throw new ServiceException(ResultCodeEnum.FAILED_NOT_SUPPORT_PROGRAM);
    }

    @Override
    public boolean rabbitSubmit(UserSubmitDTO userSubmitDTO) {
        // 先判断语言类型
        if (ProgramType.JAVA.getCode().equals(userSubmitDTO.getProgramType())) {
            // 按照java逻辑处理
            JudgeSubmitDTO judgeSubmitDTO = assembleJudgeSubmitDTO(userSubmitDTO);
            // 存入rabbitmq
            judgeProducer.produceMsg(judgeSubmitDTO);
            return true;
        }
        throw new ServiceException(ResultCodeEnum.FAILED_NOT_SUPPORT_PROGRAM);
    }

    @Override
    public UserQuestionResultVO exeResult(Long examId, Long questionId, String currentTime) {
        Long userId = ThreadLocalUtil.get(Constants.THREAD_LOCAL_USER_ID, Long.class);
        UserQuestionResultVO userQuestionResultVO = new UserQuestionResultVO();
        // 数据库中查询有无判题结果
        UserSubmit userSubmit = userSubmitMapper.selectCurrentUserSubmit(questionId, examId, userId, currentTime);
        if(userSubmit == null) {
            userQuestionResultVO.setPass(QuestionResType.IN_JUDGE.getValue());
        } else {
            userQuestionResultVO.setPass(userSubmit.getPass());
            userQuestionResultVO.setExeMessage(userSubmit.getExeMessage());
//            userQuestionResultVO.setScore(userSubmit.getScore());
            if (StrUtil.isNotEmpty(userSubmit.getCaseJudgeRes())) {
                userQuestionResultVO.setUserExeResultList(JSON.parseArray(userSubmit.getCaseJudgeRes(), UserExeResult.class));
            }
        }
        return userQuestionResultVO;
    }

    private JudgeSubmitDTO assembleJudgeSubmitDTO(UserSubmitDTO userSubmitDTO) {
        Long userId = ThreadLocalUtil.get(Constants.THREAD_LOCAL_USER_ID, Long.class);
        // 从es中查询题目信息
        QuestionES questionES = questionRepository.findById(userSubmitDTO.getQuestionId()).orElse(null);
        JudgeSubmitDTO judgeSubmitDTO = new JudgeSubmitDTO();
        if (questionES != null) {
            BeanUtil.copyProperties(questionES, judgeSubmitDTO);
        } else {
            questionES = new QuestionES();
            // 从数据库中拿  并且同步到es中
            Question question = questionMapper.selectById(userSubmitDTO.getQuestionId());
            BeanUtil.copyProperties(question, judgeSubmitDTO);
            BeanUtil.copyProperties(question, questionES);
            questionRepository.save(questionES);
            log.info("questionES:{}",questionES);
        }
        judgeSubmitDTO.setUserId(userId);
        judgeSubmitDTO.setExamId(userSubmitDTO.getExamId());
        judgeSubmitDTO.setProgramType(userSubmitDTO.getProgramType());
        judgeSubmitDTO.setUserCode(splitCode(userSubmitDTO.getUserCode(), questionES.getMainFunc()));  // 拼装完毕的可执行的总代码
        List<QuestionCase> questionCaseList = JSONUtil.toList(questionES.getQuestionCase(), QuestionCase.class);
        List<String> inputList = questionCaseList.stream().map(QuestionCase::getInput).toList();
        judgeSubmitDTO.setInputList(inputList);
        List<String> outputList = questionCaseList.stream().map(QuestionCase::getOutput).toList();
        judgeSubmitDTO.setOutputList(outputList);
        return judgeSubmitDTO;
    }

    private String splitCode(String userCode, String mainCode) {
        int endIndex = userCode.lastIndexOf("}");
        if (endIndex == -1) {
            throw new ServiceException("代码规范，请不要更改原有代码~");
        }
        return userCode.substring(0, endIndex) + "\n" + mainCode + "\n" + "}";
//        return userCode.substring(0, endIndex) + "\n" + mainCode + "\n" + userCode.substring(endIndex);
    }
}
